import json

from django.http import JsonResponse
from django.shortcuts import render
from django_redis import get_redis_connection
from goods.models import MXgoods
from common.get_cart_data import get_cart_data,save_cart_data

# Create your views here.
def cart(request):
    cart_data = get_cart_data(request)

    cart_lists = []
    if cart_data:
        for gid in cart_data:
            good = MXgoods.objects.get(id=int(gid))
            cart_dict = {
                'id':good.id,
                'img':good.img,
                'name':good.name,
                'price':good.dis,
                'num':cart_data[gid]['num'],
                'selected':cart_data[gid]['selected']
            }
            cart_lists.append(cart_dict)
    print(cart_lists)
    context = {
        'cart_lists':cart_lists
    }
    return render(request,'cart.html',context)


def status(request):
    seleted = request.POST.get('select')
    cart_data = get_cart_data(request)


    if seleted == 'false':
        for gid in cart_data:
            cart_data[gid]['selected'] = '0'
    else:
        for gid in cart_data:
            cart_data[gid]['selected'] = "1"
    res = save_cart_data(request,cart_data)
    return res
    # cart_data = json.dumps(cart_data)
    # if request.user:
    #     redis_cli = get_redis_connection('cart')
    #     redis_cli.set('redis_data_%d'%request.user.id,cart_data)
    #     return JsonResponse({'res': 'ok'})
    # else:
    #     res = JsonResponse({'res': 'ok'})
    #     res.set_cookie('cookie_data', cart_data)
    #     return res


def delgood(request):
    id = request.POST.get('gid')
    print(id)
    print(type(id))
    cart_data = get_cart_data(request)
    print(cart_data)
    for gid in list(cart_data.keys()):
        if gid == id:
            del cart_data[gid]

    res = save_cart_data(request,cart_data)
    return res
    # cart_data = json.dumps(cart_data)
    # if request.user:
    #     redis_cli = get_redis_connection('cart')
    #     redis_cli.set('redis_data_%d' % request.user.id, cart_data)
    #     return JsonResponse({'res': 'ok'})
    # else:
    #     res = JsonResponse({'res': 'ok'})
    #     res.set_cookie('cookie_data', cart_data)
    #     return res